package cn.chinaunicom.dingtalk.runner;

import cn.chinaunicom.dingtalk.sender.entity.interactive.*;
import cn.chinaunicom.dingtalk.sender.service.IDingTalkService;
import cn.hutool.json.JSONObject;
import com.dingtalk.open.app.api.OpenDingTalkClient;
import com.dingtalk.open.app.api.callback.OpenDingTalkCallbackListener;
import com.dingtalk.open.app.api.security.AuthClientCredential;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.dingtalk.open.app.api.OpenDingTalkStreamClientBuilder;

import javax.annotation.Resource;


@Component
public class ApplicationRunnerImpl implements ApplicationRunner {

    @Value("${dingtalk.endpoint}")
    private String endpoint;
    @Value("${dingtalk.protocol}")
    private String protocol;
    @Value("${dingtalk.appkey}")
    private String appkey;
    @Value("${dingtalk.appseret}")
    private String appseret;
    private final Map<String, OpenDingTalkClient> openDingTalkClientMap = new HashMap<>();

    @Resource
    private IDingTalkService dingTalkService;

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.err.println(jdbcTemplate);
        cardListener();
//        botMessageListener();
    }


    private void cardListener() {
        try {
            System.err.println("cardListener");
            OpenDingTalkStreamClientBuilder openDingTalkStreamClientBuilder = OpenDingTalkStreamClientBuilder
                    .custom();
            openDingTalkStreamClientBuilder.credential(new AuthClientCredential(appkey, appseret));
            //注册卡片回传监听器
            openDingTalkStreamClientBuilder.registerCallbackListener("/v1.0/card/instances/callback", (OpenDingTalkCallbackListener<CardCallbackRequest, CardCallbackResponse>) request -> {
                JSONObject cardResponseBody = new JSONObject(request);
                System.err.println(cardResponseBody.toString());
                CardResponseBody body = new CardResponseBody(cardResponseBody);
                InteractiveCardVo updateCard = new InteractiveCardVo();
                String outTrackId = body.getOutTrackId();
                updateCard.setOutTrackId(outTrackId);
                CardContent cardData = new CardContent();
                Map<String, String> cardParamMap = new HashMap<>();
                cardParamMap.put("btn_click", "1");
                cardData.setCardParamMap(cardParamMap);
                updateCard.setCardData(cardData);
                try {
                    dingTalkService.updateInteractiveCards(updateCard);
                    SimpleDateFormat myFmt=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                    String updateSql = "update dp_gas_stations_send_card set  btn_status = '1'," +
                            "read_time = '" + myFmt.format(new Date()) + "' " +
                            "where ding_id = '" + body.getUserId() + "' " +
                            "and out_track_id = '" + body.getOutTrackId() + "' ";

                    jdbcTemplate.execute(updateSql);

                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                return new CardCallbackResponse();
            });
            openDingTalkStreamClientBuilder.openApiHost(protocol + "://" + endpoint).build().start();
        } catch (Exception e) {
            System.err.println("cardLister超市");
        }
    }


    private void botMessageListener() throws Exception {
        OpenDingTalkStreamClientBuilder openDingTalkStreamClientBuilder = OpenDingTalkStreamClientBuilder
                .custom();
        openDingTalkStreamClientBuilder.credential(new AuthClientCredential(appkey, appseret));
        //注册机器人监听器
        openDingTalkStreamClientBuilder.registerCallbackListener("/v1.0/im/bot/messages/get", robotMessage -> {
            System.err.println("收到机器人消息：" + robotMessage);
            JSONObject message = new JSONObject(robotMessage);
            new RobotRevMessage(message);
            //开发者根据自身业务需求，处理机器人回调
            return new JSONObject();
        });
        openDingTalkStreamClientBuilder.openApiHost(protocol + "://" + endpoint).build().start();
    }
}